﻿using System;
using System.Windows;
using System.Windows.Navigation;
using AddressManager.Business.ViewModels;
using AddressManager.Common.Event;
using AddressManager.Controls.UserControls.MessageBox;

namespace AddressManager.Business.Views
{
    public partial class AddContact
    {
        readonly AddContactViewModel _viewModel;

        public AddContact()
        {
            InitializeComponent();

            _viewModel = new AddContactViewModel();
            DataContext = _viewModel;

            _viewModel.EntityAdded += ViewModelEntityAdded;
            _viewModel.PinSetted += ViewModelPinSetted;
            _viewModel.ErrorRaised += ViewModelErrorRaised;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _viewModel.Reset();
        }

        private void SearchAddress_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.SearchAddress();
        }

        void ViewModelPinSetted(object sender, EventArgs e)
        {
            if (ContactPin.Location != null)
            {
                ContactAddressMap.SetView(ContactPin.Location, 12);    
            }
        }

        private void AddNewContact_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.AddNewContact();
        }

        private void ViewModelEntityAdded(object sender, EventArgs e)
        {
            var eventArgs = (AddressManagerEventArgs)e;

            var infoBox = new InformationMessageBox(eventArgs.Info);
            infoBox.Closed += InfoBoxClosed;
            infoBox.Show();
        }

        private void InfoBoxClosed(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
        }

        static void ViewModelErrorRaised(object sender, EventArgs e)
        {
            var eventArgs = (AddressManagerEventArgs)e;

            var infoBox = new InformationMessageBox(eventArgs.Info);
            infoBox.Show();
        }

        private void Abort_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
        }
    }
}